
package com.test.util;

import lombok.Data;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public class CSVUtil {

    public static final String COMMA = ",";

    public static final String LINEFEED = "\r";

    /**
     * 生成为CSV文件内容
     *
     * @param exportData 源数据List
     * @return
     */
    public static String createCSVFileContents(List<Object> exportData) {
        StringBuilder fileContents = new StringBuilder();
        if (!CollectionUtils.isEmpty(exportData)) {
            fileContents = readAttributeValue(exportData.get(0), true);
            for (Object exportDatum : exportData) {
                fileContents.append(readAttributeValue(exportDatum, false));
            }
        }

        return fileContents.toString();
    }

    /**
     * 得到属性值
     *
     * @param obj
     * @return
     */
    public static StringBuilder readAttributeValue(Object obj, boolean flag) {
        StringBuilder nameVlues = new StringBuilder();
        //得到class
        Class cls = obj.getClass();
        //得到所有属性
        Field[] fields = cls.getDeclaredFields();
        for (Field field : fields) {
            try {
                //打开私有访问
                field.setAccessible(true);
                //获取属性
                String name = field.getName();
                //获取属性值
                Object value = field.get(obj);
                //一个个赋值
                if ("serialVersionUID".equals(name)) {
                    continue;
                }
                if (flag) {
                    nameVlues.append(name).append(COMMA);
                } else {
                    String handleStr = "";
                    if (value != null) {
                        handleStr = value.toString();
                        //先判断字符里是否含有逗号
                        if (value.toString().contains(",")) {
                            //如果还有双引号，先将双引号转义，避免两边加了双引号后转义错误
                            if (value.toString().contains("\"")) {
                                handleStr = value.toString().replace("\"", "\"\"");
                            }
                            //将逗号转义
                            handleStr = "\"" + handleStr + "\"";

                        }
                    }
                    nameVlues.append(handleStr).append(COMMA);

                }
            } catch (IllegalAccessException e) {
                System.out.println(String.format("属性：%s，解析异常", obj) + e);
            }
        }
        //获取最后一个逗号的位置
        int lastIndex = nameVlues.lastIndexOf(COMMA);

        //不要最后一个逗号","
        return new StringBuilder(nameVlues.substring(0, lastIndex)).append(LINEFEED);
    }

    public static void main(String[] args) {
        List<Object> exportData = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            TestCSV testCSV = new TestCSV();
            testCSV.setName("小刘" + i);
            testCSV.setUserName("哈哈" + i);
            exportData.add(testCSV);

        }
        //todo 待补充为输出csv文件
        System.out.println(createCSVFileContents(exportData));
        //正确结果应是
        //name,userName
        //小刘0,哈哈0
        //小刘1,哈哈1

        //实际结果  --  debug看到结果和正确结果一致
        //问题是LINEFEED 的 \r 识别问题
        //小刘1,哈哈1


    }

}

@Data
class TestCSV {
    private String name;
    private String userName;
}